﻿//----------------------------------------------------
//    版权：
//    作者：
//建立时间：2012-09-11 00:00:33
//    描述：
//----------------------------------------------------
using System;
using System.Data;
using System.Text;
using System.Collections.Generic;

using System.Linq;

using WinnerCMS.Common;
using WinnerCMS.Model;

namespace WinnerCMS.Data
{
    /// <summary>
    /// 数据访问层CMS_GoodsCustomField。
    /// </summary>
    public class GoodsCustomFieldsDal
    {

        #region  添加数据
        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="model"></param>
        public void Add(GoodsCustomField model)
        {
            using (Entities db = new Entities())
            {
                var info = db.GoodsCustomFields.Where(x => x.ModelId == model.ModelId && x.CategoryId == model.CategoryId && x.FieldName == model.FieldName);

                if (info.Any() == false)
                {
                    db.GoodsCustomFields.Add(model);
                    db.SaveChangesAsync().Wait();
                }
            }
        }
        #endregion

        #region  删除数据
        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="SelectFields"></param>
        /// <param name="CategoryId"></param>
        public void Delete(IList<string> SelectFields, int CategoryId)
        {
            if (SelectFields.Count == 0)
            {
                using (Entities db = new Entities())
                {
                    db.Database.ExecuteSqlCommand("delete from CMS_GoodsCustomField where CategoryId={0}", CategoryId);
                }
            }
            else
            {

                StringBuilder strFields = new StringBuilder();
                strFields.Append("'");
                foreach (string Field in SelectFields)
                {
                    strFields.Append(Field);
                    strFields.Append("','");
                }
                strFields.Append("'");

                StringBuilder strSql = new StringBuilder();
                strSql.Append("delete from CMS_GoodsCustomField ");
                strSql.Append(" where FieldName Not in (" + strFields + ") AND CategoryId={0}");


                using (Entities db = new Entities())
                {
                    db.Database.ExecuteSqlCommand(strSql.ToString(), CategoryId);
                }
            }
        }

        #endregion

        #region 取得该栏目使用的自定义字段
        /// <summary>
        /// 取得该栏目使用的自定义字段
        /// </summary>
        /// <param name="CategoryId"></param>
        /// <returns></returns>
        public IList<GoodsCustomField> GetFieldsList(int CategoryId)
        {
            using (Entities db = new Entities())
            {
                return db.GoodsCustomFields.Where(x => x.CategoryId == CategoryId).ToList();
            } 
        }
        #endregion

    }
}